package com.base.cn.platform.os.controller.mobile.course;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.common.constants.CacheConstants;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.common.utils.count.PageFrom;
import com.base.cn.platform.os.common.utils.count.PageKeyUtils;
import com.base.cn.platform.os.common.utils.course.CourseContentUtil;
import com.base.cn.platform.os.common.utils.course.CourseType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.op.coupon.OpCoupon;
import com.base.cn.platform.os.service.course.catalog.CourseCatalogService;
import com.base.cn.platform.os.service.course.cou.CourseService;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.count.PageViewCountService;
import com.base.cn.platform.os.service.manage.op.activity.OpActivityService;
import com.base.cn.platform.os.service.manage.op.advert.OpAdvertService;
import com.base.cn.platform.os.service.manage.op.coupon.OpCouponService;
import com.base.cn.platform.os.service.manage.teacher.SysTeacherService;
import com.base.cn.platform.os.service.manage.user.integral.CusUserIntegralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * H5课程Controller
 *
 * @author s.li
 * @create 2018-05-11-17:33
 */
@Controller
@RequestMapping("/mobile/course")
public class MobileCourseController extends MobileBaseController {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseCatalogService courseCatalogService;
    @Autowired
    private OpAdvertService opAdvertService;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;
    @Autowired
    private SysTeacherService sysTeacherService;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private PageViewCountService pageViewCountService;
    @Autowired
    private OpActivityService opActivityService;
    @Autowired
    private OpCouponService opCouponService;
    @Autowired
    private CusUserIntegralService cusUserIntegralService;

    /**
     * 加载首页广告图片
     * @return
     */
    @RequestMapping("/advertList")
    @ResponseBody
    public Map<String,Object> advertList(){
         Map<String, Object> params = new HashMap<>();
         params.put("placeKey", "APPBANNER");
         params.put("status", 1);
         List<Map<String, Object>> advertList = opAdvertService.queryAdvertList(params, false, false, false);
         return ResultUtil.SUCCESS(advertList);
    }

    /**
     * 跳转选课页面 -- 推荐
     * @return
     */
    @RequestMapping("/recommend/index")
    public String recommendIndex(Model model, HttpServletRequest request){
        return resultPage("/course/recommend-list");
    }

    /**
     * 跳转选课分类页面
     * @return String
     */
    @RequestMapping("/classify/index")
    public String toClassifyIndex() {
        return resultPage("/course/classify-index");
    }

    /**
     * 课程列表
     * @return
     */
    @RequestMapping("/courseList")
    public String courseList(Model model,
                             @RequestParam(value = "subjectIds", required = false) String subjectIds,
                             @RequestParam(value = "keyword", required = false) String keyword){
        model.addAttribute("subjectIds", subjectIds);
        model.addAttribute("keyword", keyword);
        model.addAttribute("courseTypeList", CourseType.values());
        return resultPage("/course/course-list");
    }

    /**
     * 加载课程列表数据
     * @param model
     * @param params 查询条件
     * @param currentPage 页码
     * @return 列表页面
     */
    @RequestMapping("/ajaxCourseList")
    public String ajaxCourseList(Model model,
                                 @RequestBody Map<String,Object> params,
                                 @RequestParam(value = "currentPage",required = false,defaultValue = "0")  int currentPage){
        params.put("status",1);
        params.put("type",1);
        params.put("notCourseTypeKeys","'LIVE'");
        Map<String,Object> dataMap = courseService.findWebCoursePage(params,currentPage,10,true,false,false,true,false);
        model.addAttribute("dataMap",dataMap);
        if(params.get("invite")!=null){
            model.addAttribute("invite", true);
        }
        return resultPage("/course/ajax-course-list");
    }

    /**
     * 加载老师课程列表数据
     * @param model
     * @param params 查询条件
     * @param currentPage 页码
     * @return 列表页面
     */
    @RequestMapping("/ajaxTeacherCourseList")
    public String ajaxTeacherCourseList(Model model,
                                 @RequestBody Map<String,Object> params,
                                 @RequestParam(value = "currentPage",required = false,defaultValue = "0")  int currentPage){
        params.put("status",1);
        params.put("type",1);
        params.put("notCourseTypeKeys","'PACKAGE'");
        Map<String,Object> dataMap = courseService.findWebCoursePage(params,currentPage,10,false,false,false,true,false);
        model.addAttribute("dataMap",dataMap);
        return resultPage("/course/ajax-teacher-course-list");
    }

    /**
     * 查看课程详情
     * @param request HttpServletRequest
     * @param courseId 课程/套餐ID
     * @param packageCourseId 套餐下的课程ID
     * @param catalogId 播放的目录ID
     * @param classFrom 1表示是从班级引导购买课程
     * @return String
     */
    @RequestMapping("/info")
    public String courseInfo(HttpServletRequest request,
                             Model model,
                             @RequestParam("courseId") BigDecimal courseId,
                             @RequestParam(value = "packageCourseId",required = false,defaultValue = "0") BigDecimal packageCourseId,
                             @RequestParam(value = "catalogId",required = false,defaultValue = "0") BigDecimal catalogId,
                             @RequestParam(value = "classFrom",required = false,defaultValue = "0")int classFrom,
                             @RequestParam(value = "shareKey",required = false)String shareKey
    ){
        // 分享成功 给分享人添加积分
        Boolean isLogin = webMobileLoginUtil.isLogin(request);
        if (StringUtils.isNotEmpty(shareKey)&&isLogin) {
            String cookie = WebUtils.getCookie(request, "shareKey");
            if (!shareKey.equals(cookie)||StringUtils.isEmpty(cookie)) {
                BigDecimal shareUserId= new BigDecimal( shareKey.split("_")[1]);
                cusUserIntegralService.addUserIntegral(ActionKey.SHARE, shareUserId, shareUserId, 0, 2);
            }
        }
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Course course = courseService.findToBuyCourseManyById(courseId,userId,true,true,true,false,false,true,true);
        model.addAttribute("course",course);
        model.addAttribute("packageCourseId",packageCourseId);
        model.addAttribute("catalogId",catalogId);
        model.addAttribute("shareKey", shareKey);
        String backUrl = "/mobile/course/courseList";
        String Referer = request.getHeader("Referer");
        if(StringUtils.isNotEmpty(Referer)){
            backUrl = Referer;
        }
        model.addAttribute("backUrl",backUrl);
        String classesUrl = "";
        Map<String, Object> map = (Map<String, Object>) customCacheChannel.get(J2CacheRegion.THIRD_MINUTE_REGION.getKey(), CacheConstants.USER_BUY_COURSE_JOIN_CLASS + userId.toString()).getValue();
        if (classFrom == 1 && StringUtils.isNotEmpty(map)){
            int _courseId = (Integer) map.get("courseId");
            if (courseId.intValue() ==_courseId){
                String classesUrl1 = (String) map.get("classesUrl");
                classesUrl = classesUrl1;
            }
            Double realPrice = course.getRealPrice();
            if (realPrice <= 0){
                customCacheChannel.evict(J2CacheRegion.THIRD_MINUTE_REGION.getKey(), CacheConstants.USER_BUY_COURSE_JOIN_CLASS + userId.toString());
            }
        }else{
            customCacheChannel.evict(J2CacheRegion.THIRD_MINUTE_REGION.getKey(), CacheConstants.USER_BUY_COURSE_JOIN_CLASS + userId.toString());
        }
        model.addAttribute("classesUrl",classesUrl);
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.VLASPROVIDER);
        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_MOBILE);
        String vlasType = configMap.get("type");
        course.setCourseService(setCourseService(Integer.valueOf(course.getService())));
        model.addAttribute("vlasType",vlasType);
        return resultPage("/course/course-info");
    }

    /**
     * 直播首页（列表）
     * @return
     */
    @RequestMapping("/liveIndex")
    public String newLiveIndex(){
        return resultPage("/course/live/live-index");
    }

    /**
     * 加载直播课程数据
     * @param model Model
     * @param params 参数
     * @param currentPage 页码
     * @return
     */
    @RequestMapping("/ajaxLiveIndex")
    public String ajaxLiveIndex(Model model,
                                @RequestBody Map<String, Object> params,
                                @RequestParam("currentPage") int currentPage){
        params.put("status", 1);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_LIVE.getKey());
        params.put("type", 1);
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 4, true, false, false, true,true);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/live/ajax-live-index");
    }

    /**
     * 直播详情
     * @param  courseId 直播课程ID
     * @param  catalogId 默认播放的目录ID
     * @return 操作页面
     */
    @RequestMapping("/liveInfo")
    public String newLiveInfo(HttpServletRequest request,
                              Model model,
                              @RequestParam("courseId") BigDecimal courseId,
                              @RequestParam(value = "catalogId",required = false,defaultValue = "0") BigDecimal catalogId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        model.addAttribute("course",course);
        model.addAttribute("catalogId",catalogId);
        String backUrl = "/mobile/course/liveIndex";
        String Referer = request.getHeader("Referer");
        if(StringUtils.isNotEmpty(Referer)){
            backUrl = Referer;
        }
        course.put("courseService",setCourseService(Integer.valueOf(course.get("service").toString())));

        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_MOBILE);
        model.addAttribute("backUrl",backUrl);
        return resultPage("/course/live/live-info");
    }

    /**
     * 获取直播课程目录
     * @param courseId 课程ID
     * @return  目录页面
     */
    @RequestMapping("/findLiveCatalog")
    public String findLiveCatalog(HttpServletRequest request,
                                  Model model,
                                  @RequestParam("courseId") BigDecimal courseId){
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String,Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(courseId,userId,courseId,true, false, false, false,true);
        model.addAttribute("courseCatalogList",courseCatalogList);
        return resultPage("/course/live/ajax-live-info-catalog");
    }

    /**
     * 获取课程目录
     * @param courseId 课程ID
     * @return  目录页面
     */
    @RequestMapping("/findCourseCatalog")
    public String findCourseCatalog(HttpServletRequest request,
                                    Model model,
                                    @RequestParam("buyCourseId") BigDecimal buyCourseId,
                                    @RequestParam("courseId") BigDecimal courseId){
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<Map<String,Object>> courseCatalogList = courseCatalogService.findCourseCatalogLayeredByCourseId(buyCourseId,userId,courseId,true, false, false, false,true);
        model.addAttribute("courseCatalogList",courseCatalogList);
        return resultPage("/course/ajax-course-info-catalog");
    }

    /**
     * 通过讲师ID，获取讲师数据
     * @param teacherId 课程ID
     * @return Map<String,Object>
     */
    @RequestMapping("/findQaTeacherById")
    @ResponseBody
    public Map<String,Object> findQaTeacherById(@RequestParam("teacherId") BigDecimal teacherId){
        Map<String,Object> teacher = sysTeacherService.findQaTeacherById(teacherId);
        return ResultUtil.SUCCESS("查询成功",teacher);
    }

    /**
     *  检查是否购买课程/套餐
     *
     * @param courseId 课程id
     */
    @RequestMapping("/ajax/check/buy")
    @ResponseBody
    public Map<String, Object> checkBuy(HttpServletRequest request,
                                        @RequestParam("courseId") BigDecimal courseId) {
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> result = courseBuyRecordService.checkUserBuyCourse(userId,courseId);
        if (ObjectUtils.isNotEmpty(result)){
           if (CourseType.COURSE_TYPE_PACKAGE.getKey().equals(result.get("courseTypeKey"))){
               if (!result.get("status").equals(1)){
                return ResultUtil.ERROR("套餐激活后才能评价与反馈");
               }
           }
       }else {
            return ResultUtil.ERROR("您还没有购买此课程");
        }
        return ResultUtil.SUCCESS();
    }



    /**
     * 用于引导用户去购买课程
     * @param request HttpServletRequest
     * @param courseId 课程ID
     * @return 详情页面
     */
    @RequestMapping("/guideBuyCourse")
    @ResponseBody
    public Map<String,Object> guideBuyCourse(HttpServletRequest request,
                                             @RequestParam("courseId") BigDecimal courseId) {
        //用户ID
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);

        return   courseService.guideBuyCourse(courseId, userId,true, true, false, false, false, false,false);
    }

    /**
     * 下载课程章节资料
     * @param catalogId 课程id
     */
    @RequestMapping("/downloadDatum")
    public ResponseEntity<byte[]> downloadDatum(@RequestParam("catalogId") BigDecimal catalogId ) throws Exception {
        return courseCatalogService.downloadDatum(catalogId);
    }

    /**
     * 获取最新更新的目录数据
     * @param courseIds
     * @return Map<String,Object>
     */
    @RequestMapping("/getNewCatalog")
    @ResponseBody
    public Map<String,Object> getNewCatalog(@RequestParam("courseIds") String courseIds){
        Map<String,Object> catalog = courseCatalogService.getNewCourseCatalog(courseIds);
        return ResultUtil.SUCCESS(catalog);
    }

    /**
     * 查询课程详情可以显示的活动
     * @param price 课程价格
     * @return Map<String,Object>
     */
    @RequestMapping("/getCourseInfoActivity")
    @ResponseBody
    public Map<String,Object> getCourseInfoActivity(@RequestParam(value = "price",required = false,defaultValue = "0") Double price){
        List<Map<String,String>> params = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("price",String.valueOf(price));
        params.add(map);
        return ResultUtil.SUCCESS(opActivityService.findOrderAvailableActivityList(params,false));
    }

    /**
     * 获取课程可以领取的优惠券数据列表
     * @param courseId 课程ID
     * @return Map<String,Object>
     */
    @RequestMapping("/getCourseCouponList")
    @ResponseBody
    public Map<String,Object> getCourseCouponList(HttpServletRequest request,
                                                  @RequestParam("courseId") BigDecimal courseId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        List<OpCoupon> couponList = opCouponService.getCourseCouponList(courseId,userId);
        return ResultUtil.SUCCESS(couponList);
    }



    private String setCourseService(Integer service){
      return   CourseContentUtil.setCourseService(service,sysConfigService," . ");

    }


    /************************小班课*************************/
    /**
     * 小班课（列表）
     * @return
     */
    @RequestMapping("/smallClassIndex")
    public String smallClassIndex(){
        return resultPage("/course/smallClass/smallClass-index");
    }

    /**
     * 加载小班课数据
     * @param model Model
     * @param params 参数
     * @param currentPage 页码
     * @return
     */
    @RequestMapping("/ajaxSmallClassList")
    public String ajaxSmallClass(Model model,
                                 @RequestBody Map<String, Object> params,
                                 @RequestParam("currentPage") int currentPage){
        params.put("status", 1);
        params.put("courseTypeKey", CourseType.COURSE_TYPE_SMALL.getKey());
        params.put("type", 1);
        Map<String, Object> dataMap = courseService.findWebCoursePage(params, currentPage, 4, true, false, false, true,false);
        model.addAttribute("dataMap", dataMap);
        return resultPage("/course/smallClass/smallClass-ajax-list");
    }


    /**
     * 小班课（详情）
     * @return
     */
    @RequestMapping("/smallClassInfo")
    public String smallClassInfo(HttpServletRequest request,
                                 Model model,
                                 @RequestParam("courseId") BigDecimal courseId,
                                 @RequestParam(value = "catalogId",required = false,defaultValue = "0") BigDecimal catalogId){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String, Object> course = courseService.findToBuyCourseById(courseId, userId,true, true, true, false, false, true,true);
        model.addAttribute("course",course);
        model.addAttribute("catalogId",catalogId);
        String backUrl = "/mobile/course/smallClassInfo";
        String Referer = request.getHeader("Referer");
        if(StringUtils.isNotEmpty(Referer)){
            backUrl = Referer;
        }
        course.put("courseService",setCourseService(Integer.valueOf(course.get("service").toString())));

        pageViewCountService.addPageCount(PageKeyUtils.COURSE_INFO, PageFrom.PAGE_FROM_MOBILE);
        model.addAttribute("backUrl",backUrl);
        return resultPage("/course/smallClass/smallClass-info");
    }

}
